<template>
  <div>
    <div class="layui-container fly-marginTop">
      <div class="fly-panel fly-panel-user"
           pad20>
        <div class="layui-tab layui-tab-brief"
             lay-filter="user">
          <ul class="layui-tab-title">
            <li class="layui-this">登入</li>
            <li>
              <router-link :to="{ name: 'reg' }">注册</router-link>
            </li>
          </ul>
          <div class="layui-form layui-tab-content"
               id="LAY_ucm"
               style="padding: 20px 0;">
            <validation-observer ref="observer"
                                 v-slot="{ validate }">
              <div class="layui-tab-item layui-show">
                <div class="layui-form layui-form-pane">
                  <form method="post">
                    <div class="layui-form-item">
                      <label for="L_email"
                             class="layui-form-label">用户名</label>
                      <validation-provider rules="required|email"
                                           v-slot="{ errors }"
                                           name="username">
                        <div class="layui-input-inline">
                          <input type="text"
                                 id="L_email"
                                 name="email"
                                 class="layui-input"
                                 autocomplete="off"
                                 v-model="username"
                                 placeholder="请输入用户名">
                        </div>
                        <div class="layui-form-mid">
                          <span style="color: #c00">{{ errors[0] }}</span>
                        </div>
                      </validation-provider>
                    </div>
                    <div class="layui-form-item">
                      <label for="L_pass"
                             class="layui-form-label">密码</label>
                      <validation-provider rules="required|min:6|max:16"
                                           v-slot="{ errors }"
                                           name="password">
                        <div class="layui-input-inline">
                          <input type="password"
                                 id="L_pass"
                                 name="pass"
                                 class="layui-input"
                                 v-model="password"
                                 placeholder="请输入密码">
                        </div>
                        <div class="layui-form-mid">
                          <span style="color: #c00">{{ errors[0] }}</span>
                        </div>
                      </validation-provider>
                    </div>
                    <div class="layui-form-item">
                      <label for="L_vercode"
                             class="layui-form-label">验证码</label>
                      <validation-provider name="code"
                                           ref="codefield"
                                           rules="required|length:4"
                                           v-slot="{ errors }">
                        <div class="layui-input-inline">
                          <input type="text"
                                 id="L_vercode"
                                 name="vercode"
                                 placeholder="请输入验证码"
                                 class="layui-input"
                                 v-model="code">
                        </div>
                        <div>
                          <span class="svg"
                                style="color: #c00;"
                                v-html="svg"
                                @click="_getCode()"></span>
                        </div>
                        <div>
                          <span style="color: #c00">{{ errors[0] }}</span>
                        </div>
                      </validation-provider>
                    </div>
                    <div class="layui-form-item">
                      <button class="layui-btn"
                              type="button"
                              @click="validate().then(submit)">立即登录</button>
                      <span style="padding-left:20px;">
                        <router-link :to="{ name: 'forget' }">忘记密码</router-link>
                      </span>
                    </div>
                  </form>
                </div>
              </div>
            </validation-observer>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCode, login } from '@/api/login'
import uuid from 'uuid/dist/v4'
import { ValidationProvider, ValidationObserver } from 'vee-validate'
export default {
  name: 'login',
  components: {
    ValidationProvider,
    ValidationObserver
  },
  data () {
    return {
      username: '',
      password: '',
      code: '',
      svg: ''
    }
  },
  mounted () {
    let sid = ''
    if (localStorage.getItem('sid')) {
      sid = localStorage.getItem('sid')
    } else {
      sid = uuid()
      localStorage.setItem('sid', sid)
    }
    this.$store.commit('setSid', sid)
    // console.log(sid)
    this._getCode(sid)
  },
  methods: {
    _getCode () {
      const sid = this.$store.state.sid
      getCode(sid).then((res) => {
        if (res.code === 200) {
          this.svg = res.data
        }
      })
    },
    async submit () {
      // 判断前端验证表单是否全部通过
      const isValid = await this.$refs.observer.validate()
      if (!isValid) {
        return
      }
      login({
        username: this.username,
        password: this.password,
        code: this.code,
        sid: this.$store.state.sid
      })
        .then((res) => {
          if (res.code === 200) {
            // 这里username后台没传过来，所以这里插值
            res.data.username = this.username
            // 提交到VueX
            this.$store.commit('setUserInfo', res.data)
            this.$store.commit('setToken', res.token)
            this.$store.commit('setIsLogin', true)
            // 清空表单
            this.username = ''
            this.password = ''
            this.code = ''
            // 清空错误的校验信息
            requestAnimationFrame(() => {
              this.$refs.observer && this.$refs.observer.reset()
            })
            // 导航到首页
            this.$router.push('/')
          } else if (res.code === 401) {
            this.$refs.codefield.setErrors([res.msg])
          } else if (res.code === 404) {
            this.$alert(res.msg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
